package com.atguigu.demojuc.chap02;

import java.util.concurrent.locks.ReentrantLock;

class Ticket{
    private final ReentrantLock lock = new ReentrantLock();
    //  定义一个票数
    private int number = 21;
    //  定义一个卖票的方法:
    public void sale(){
        lock.lock();
        if (number<=0){
            System.out.println(Thread.currentThread().getName()+"票买没了");
            lock.unlock();
            return;
        }
        try {
            System.out.println(Thread.currentThread().getName() + "开始买票，当前票数：" + number);
            Thread.sleep(200);
            System.out.println(Thread.currentThread().getName() + "买票结束，剩余票数：" + --number);
            // 调用check方法测试锁的可重入性
            check();

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println("finally");
            lock.unlock();
        }
    }
    /**
     * 为了测试可重入锁，添加检查余票方法
     */
    public void check(){
        lock.lock();
        System.out.println("检查余票。。。。");
        lock.unlock();
    }

    public static void main(String[] args) {
        Ticket ticket = new Ticket();

        //  创建线程
        new Thread(() -> {
            for (int i = 0; i < 21; i++) {
                ticket.sale();
            }
        },"A").start();
        new Thread(() -> {
            for (int i = 0; i < 21; i++) {
                ticket.sale();
            }
        },"B").start();
        new Thread(() -> {
            for (int i = 0; i < 21; i++) {
                ticket.sale();
            }
        },"C").start();
    }
}